package com.siashan.toolkit.sms.huaweicloud.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.siashan.toolkit.sms.core.entity.*;
import com.siashan.toolkit.sms.core.exception.Unisms4jException;
import com.siashan.toolkit.sms.core.exception.Unisms4jInvalidParamException;
import com.siashan.toolkit.sms.core.executor.AbstractSmsSendExecutor;
import com.siashan.toolkit.sms.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import sun.net.www.protocol.https.DefaultHostnameVerifier;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 华为云短信通知执行器
 *
 * @author siashan
 * @since v1.0.1
 **/
@Slf4j
public class HuaWeiCloudSmsSendExecutor extends AbstractSmsSendExecutor {


    /**
     * 无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
     */
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";

    /**
     * 无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
     */
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";

    /**
     * 号码区号前缀
     */
    private static final String DEFAULT_NATION_CODE = "+86";


    /**
     * Jackson系列化
     */
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * HttpClient客户端
     */
    private final CloseableHttpClient client;


    /**
     * 华为云短信配置
     */
    private HuaWeiCloudSmsConfig huaWeiCloudSmsConfig;

    /**
     * 构造华为云短信发送处理
     *
     * @param config 华为云短信配置
     */
    public HuaWeiCloudSmsSendExecutor(HuaWeiCloudSmsConfig config) {
        super(config);
        this.huaWeiCloudSmsConfig = config;
        this.client = buildHttpclient();
    }

    /**
     * 构造华为云短信发送处理
     *
     * @param config 华为云短信配置
     */
    public HuaWeiCloudSmsSendExecutor(HuaWeiCloudSmsConfig config,Map<String, SmsTemplate> templateMap) {
        this(config);
        this.templateMap = templateMap;
    }

    /**
     * 构造华为云短信发送处理
     *
     * @param config 华为云短信配置
     */
    public HuaWeiCloudSmsSendExecutor(HuaWeiCloudSmsConfig config,Map<String, SmsTemplate> templateMap,SmsWhiteList whiteList) {
        this(config,templateMap);
        this.whiteList = whiteList;
    }

    /**
     * 构造华为云短信发送处理
     *
     * @param config 华为云短信配置
     */
    public HuaWeiCloudSmsSendExecutor(HuaWeiCloudSmsConfig config,Map<String, SmsTemplate> templateMap,SmsWhiteList whiteList,SmsFrequencyLimitConfig frequencyLimit) {
        this(config,templateMap,whiteList);
        this.frequencyLimit = frequencyLimit;
    }


    /**
     * 发送批量通知
     *
     * @param smsSendModel 通知参数
     * @return 是否发送成功
     */
    @Override
    public boolean doSend(SmsModel smsSendModel) {
        //必填,请参考"开发准备"获取如下数据,替换为实际值
        //必填,全局号码格式(包含国家码),示例:+86151****6789,多个号码之间用英文逗号分隔
        String receiver = buildReceiver(smsSendModel.getPhones());
        /**
         * 选填,使用无变量模板时请赋空值 String templateParas = "";
         * 单变量模板示例:模板内容为"您的验证码是${1}"时,templateParas可填写为"[\"369751\"]"
         * 双变量模板示例:模板内容为"您有${1}件快递请到${2}领取"时,templateParas可填写为"[\"3\",\"人民公园正门\"]"
         * 模板中的每个变量都必须赋值，且取值不能为空
         * 查看更多模板和变量规范:产品介绍>模板和变量规范
         */
        String templateParas = buildTemplateParas(smsSendModel.getParams(), null);
        //请求Body,不携带签名名称时,signature请填null
        String body = buildRequestBody(receiver, smsSendModel.getTemplateId(), templateParas);
        //请求Headers中的X-WSSE参数值
        String wsseHeader = buildWsseHeader();
        HttpResponse response = null;
        try {
            response = client.execute(RequestBuilder.create("POST")//请求方法POST
                    .setUri(huaWeiCloudSmsConfig.getUrl())
                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                    .addHeader("X-WSSE", wsseHeader)
                    .setEntity(new StringEntity(body)).build());
            String responseContent = EntityUtils.toString(response.getEntity());
            log.debug("responseContent: {}", responseContent);
            HuaWeiCloudResponse result = objectMapper.readValue(responseContent, HuaWeiCloudResponse.class);

            boolean succeed = HuaWeiCloudResponse.SUCCESS_CODE.equals(result.getCode());
            return succeed;
        } catch (IOException e) {
            throw new Unisms4jInvalidParamException("[华为云短信]发送失败", e);
        }
    }

    /**
     * 构造模板参数
     *
     * @param params 参数列表
     * @return 模板参数
     */
    private String buildTemplateParas(Map<String, String> params, String paramMapping) {
        if (params == null || params.isEmpty()) {
            return null;
        }
        List<String> paramsWithoutKey = transferParamsWithoutKey(params, paramMapping);
        String valueAsString = null;
        try {
            valueAsString = objectMapper.writeValueAsString(paramsWithoutKey);
        } catch (JsonProcessingException e) {
            throw new Unisms4jException("[华为云短信]发送失败", e);
        }

        return valueAsString;
    }

    /**
     * 构造短信接收人
     *
     * @param phones 短信接收人集合
     * @return 短信接收人
     */
    private String buildReceiver(Collection<String> phones) {
        StringBuilder receiverBuilder = new StringBuilder();
        for (String phone : phones) {
            if (StringUtils.isBlank(phone)) {
                continue;
            }
            if (!phone.startsWith("+")) {
                phone = DEFAULT_NATION_CODE + phone;
            }
            receiverBuilder.append(phone);
            receiverBuilder.append(",");
        }
        return receiverBuilder.substring(0, receiverBuilder.length() - 1);
    }

    /**
     * 构造请求Body体
     *
     * @param receiver      短信接收人
     * @param templateId    模版id
     * @param templateParas 模板参数
     * @return 请求Body体
     */
    private String buildRequestBody(String receiver, String templateId, String templateParas) {
        if (null == receiver || null == templateId || receiver.isEmpty()
                || templateId.isEmpty()) {
            throw new Unisms4jInvalidParamException("buildRequestBody(): receiver or templateId is null.");
        }
        List<NameValuePair> keyValues = new ArrayList<NameValuePair>();

        keyValues.add(new BasicNameValuePair("from", huaWeiCloudSmsConfig.getSender()));
        keyValues.add(new BasicNameValuePair("to", receiver));
        keyValues.add(new BasicNameValuePair("templateId", templateId));
        if (null != templateParas && !templateParas.isEmpty()) {
            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        }
        String statusCallBackUrl = StringUtils.trimToNull(huaWeiCloudSmsConfig.getStatusCallBackUrl());
        if (null != statusCallBackUrl && !statusCallBackUrl.isEmpty()) {
            keyValues.add(new BasicNameValuePair("statusCallback", statusCallBackUrl));
        }
        String signature = StringUtils.trimToNull(huaWeiCloudSmsConfig.getSignature());
        if (null != signature && !signature.isEmpty()) {
            keyValues.add(new BasicNameValuePair("signature", signature));
        }

        return URLEncodedUtils.format(keyValues, StandardCharsets.UTF_8);
    }

    /**
     * 构造X-WSSE参数值
     *
     * @return X-WSSE参数值
     */
    private String buildWsseHeader() {
        String appKey = huaWeiCloudSmsConfig.getAppKey();
        String appSecret = huaWeiCloudSmsConfig.getAppSecret();
        if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
            throw new Unisms4jInvalidParamException("buildWsseHeader(): appKey or appSecret is null.");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String time = sdf.format(new Date());
        String nonce = UUID.randomUUID().toString().replace("-", "");

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);

        //如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes());
        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }

    /**
     * 初始化HttpClient
     *
     * @return CloseableHttpClient
     */
    private CloseableHttpClient buildHttpclient() {
        //如果JDK版本是1.8,可使用如下代码
        try {
            CloseableHttpClient client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(new DefaultHostnameVerifier())
                    .build();
            return client;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Unisms4jException("[华为云短信]初始化HttpClient异常！");
        }
    }

    /**
     * 获取通道
     *
     * @return 通道
     */
    @Override
    public SmsChannel getChannel() {
        return SmsChannel.HUAWEI;
    }


    public static void main(String[] args) throws JsonProcessingException {
        List<String> strs = new ArrayList<>();
        strs.add("000123");
        strs.add("33333333");
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(strs);
        System.out.println(s);

        String str = "[\"000123\",\"33333333\"]";

        System.out.println(s.equals(str));
    }

}
